<?php

/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2017/6/28
 * Time: 14:38
 */

namespace Admin\Service;

use Service\BaseService;

class AccountantService extends BaseService {

    public function __construct() {
        parent::__construct();
        $this->accModel = M('accountant_users');
    }

    public function accList($cat_ids,$user_name,$mobile,$status,$city,$isPage = 1, $nowPage = 1) {

        if ($cat_ids) {
            foreach ($cat_ids as $cat_id){
                if($cat_id)
                    $temp[] = 'find_in_set('.$cat_id.',au.cat_ids)';
            }
            $where['_string'] = '('.implode(' or ',$temp).')';
        }

        if ($user_name) {
            $where['au.username'] = array('like', '%'.$user_name.'%');
        }

        if ($mobile) {
            $where['au.mobile'] = $mobile;
        }

        if (is_numeric($status) !== false) {
            $where['au.status'] = $status;
        }

        if ($city) {
            $city_id = M('region')->where(" name like '%$city%' and level = 2 ")->getField('id');
            $where['au.city'] = $city_id ? $city_id : -1;
        }

        $obj = $this->accModel->alias('au')
            ->join('left join __REGION__ as ag on ag.id = au.city')
            ->join('left join __ANSWER__ as a on a.accountant_id = au.au_id')
            ->field('au.*,ag.name as city_name,
            if(a.accountant_id > 0,count(a.accountant_id),0) as count')
             ->group('au.au_id')
             ->order('au.au_id desc');

        if ($where) {
            $obj->where($where);
        }
        if ($isPage) {
            $countRes = $obj->count();
            self::bPage($countRes);
            return self::resReturn(200, "success", self::$pageObj);
        } else {
            $lineList = $obj->page($nowPage, self::$pageNum)->select();
            return self::resReturn(200, 'success', $lineList);
        }
    }

    public function accInfo($id) {

        $find = $this->accModel
            ->where('au_id  = '.(int)$id)->find();

        return array(
            'info' => $find,
        );
    }


    public function handle($data = array()){

        $act = $data['act'];
        switch ($act){

            case 'add':

                unset($data['act']);

                if ($data['status'] == 2 && empty($data['reason'])){
                    return self::resReturn(130, '审核失败原因必填');
                }
                $data['reg_time'] = time();
                $data['expired_time'] = strtotime($data['expired_time']);
                $data['cat_ids'] = implode(',',$data['cat_ids']);
                $data['password'] = encrypt($data['password']);
                $res = $this->accModel->add($data);
                if($res){
                   $this->handleSms($data);
                }
                break;
            case 'edit':

                unset($data['act']);
                $status = $this->accModel->where('au_id = '.$data['id'])->getField('status');
                if ( $data['status'] != $status && $data['status'] == 2 && empty($data['reason'])){
                    return self::resReturn(130, '审核失败原因必填');
                }
                if($data['password']){
                    $data['password'] = encrypt($data['password']);
                }else{
                    unset($data['password']);
                }
                $data['cat_ids'] = implode(',',$data['cat_ids']);

                $data['expired_time'] = strtotime($data['expired_time']);

                $res =  M('accountant_users')->where('au_id = '.$data['id'].'')->data($data)->save();
                if($res && $data['status'] != $status){
                    $this->handleSms($data);
                }
                break;
            case 'del':
                $where['au_id'] = $data['id'];
                $res = $this->accModel->where($where)->delete();
                M('question_answer')->where('answer_id = '.$data['id'].'')->delete();
                M('answer')->where('accountant_id = '.$data['id'].'')->delete();
                break;
        }

        if ($res){
            return self::resReturn(200, '操作成功');
        } else{
            return self::resReturn(130, '操作失败');
        }

    }

    public function  handleSms($data){

        $config = M('config')->where("inc_type = 'sms' ")->select();
        foreach ($config as $val){
            $temp[$val['name']] = $val['value'];
        }
        $config = $temp;
        $reason = '';
        if($data['status'] == 1){
            $sms_code = $config['sms_apply_success'];
        }elseif ($data['status'] == 2){
            $sms_code = $config['sms_apply_fail'];
            $reason = $data['reason'];
        }else{
            return;
        }

        $options = [
            'accountsid' => $config['sms_account_sid'],
            'token' => $config['sms_token']
        ];
        $Yun = new \Org\Sms\Yun($options);
        $result = $Yun->templateSMS($config['sms_appid'], $data['mobile'], $sms_code, $data['mobile'].','.$reason, 'xml');

        $status = preg_match('/000000/', $result);
        if ($status) {
            return true;
        } else {
            return false;
        }

    }


    public function answerList($au_id,$title,$cat_ids,$status,$isPage = 1, $nowPage = 1) {

        if ($cat_ids) {
            foreach ($cat_ids as $cat_id){
                if($cat_id)
                    $temp[] = 'find_in_set('.$cat_id.',q.cat_ids)';
            }

            if($temp)
                $where['_string'] = '('.implode(' or ',$temp).')';
        }

        if ($au_id) {
            if($status == 2)
                $where['qa.answer_id'] = $au_id;
            else
                $where['a.accountant_id'] = $au_id;
        }

        if ($title) {
            $where['q.title'] = array('like' , '%'.$title.'%');
        }


        if($status == 2) { //未回答
            $where['qa.answer_id'] = $au_id;
            $where['q.answer_status'] = 1;
            $obj = M('question_answer')->alias('qa')
                ->join('left join __QUESTION__ as q on qa.question_id = q.id')
                ->join('left join __USERS__ as u on q.user_id = u.user_id')
                ->field('qa.*,q.id as q_id,q.title,q.cat_ids,q.stop_time,q.open_reward,q.reward_money,q.read_num,q.question_status,q.answer_status,q.response_sec,u.username')
                ->order('qa.id desc');
        }else{//已回答

            $where['a.accountant_id'] = $au_id;
            $where['q.answer_status'] = 2;

            $obj = M('answer')->alias('a')
                ->join('left join __QUESTION__ as q on a.question_id = q.id')
                ->join('left join __USERS__ as u on q.user_id = u.user_id')
                ->field('a.*,a.id as a_id,q.id as q_id,q.title,q.cat_ids,q.stop_time,q.open_reward,q.reward_money,q.read_num,q.question_status,q.answer_status,q.response_sec,u.username')
                ->order('a.id desc');
        }

        if ($where) {
            $obj->where($where);
        }
        if ($isPage) {
            $countRes = $obj->count();
            self::bPage($countRes);
            return self::resReturn(200, "success", self::$pageObj);
        } else {
            $lineList = $obj->page($nowPage, self::$pageNum)->select();
            return self::resReturn(200, 'success', $lineList);
        }
    }


    public function answer_handle($data = array()){

        $act = $data['act'];
        switch ($act){

            case 'add':

                unset($data['act']);

                break;
            case 'edit':

                unset($data['act']);
                $data['add_time'] = strtotime($data['add_time'] );
               $res =  M('answer')->where('id = '.$data['id'].'')->save($data);
                break;
            case 'del':

                $res = M('question')->where('id = '.$data['id'].'')->delete();

                $res = M('question_answer')->where('question_id = '.$data['id'].'')->delete();
                $res = M('answer')->where('question_id = '.$data['id'].'')->delete();
                break;
        }

        if ($res){
            return self::resReturn(200, 'success');
        } else{
            return self::resReturn(130, '操作失败');
        }

    }



}
